#!/bin/bash

# tengine的控制脚本

CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
THIS_SCRIPT="${CURRENT_DIR}/$(basename $0)"
PROJECT_FOLDER="$(dirname $(dirname ${CURRENT_DIR}))"

# 解决python的ssl依赖问题
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${PROJECT_FOLDER}/component/env/lib/

APP_NAME="tengine"

start() {
  real_status
  if [ $? -eq 0 ];then
    echo "${APP_NAME} [running]"
    return 0
  else
    $PROJECT_FOLDER/component/tengine/sbin/nginx -p $PROJECT_FOLDER/component/tengine >/dev/null  2>&1
    echo "${APP_NAME} [running]"
  fi
}

stop() {
  real_status
  if [ $? -eq 1 ]; then
    echo "${APP_NAME} [not running]"
    return 0
  else
    $PROJECT_FOLDER/component/tengine/sbin/nginx -p $PROJECT_FOLDER/component/tengine -s stop
    sleep 3
    real_status
    if [ $? -eq 0 ]; then
      echo "${APP_NAME} [running]"
      return 1
    else
      echo "${APP_NAME} [not running]"
      return 0
    fi
  fi
}

real_status() {
  tengine_status=$(ps -ef | grep nginx | grep ${PROJECT_FOLDER} | grep -v grep)
  if [ -n "$tengine_status" ]; then
    return 0
  else
    return 1
  fi
}

status() {
  real_status
  if [ $? -eq 0 ]; then
    echo "${APP_NAME} [running]"
    return 0
  else
    echo "${APP_NAME} [not running]"
    return 1
  fi
}

case $1 in
start) start ;;
stop) stop ;;
restart)
  stop
  start
  ;;
status)
  status
  ;;
*)
  echo "usage: $0 [start|stop|restart|status]"
  ;;
esac
